import 'dart:async';
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter_openim_sdk/flutter_openim_sdk.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:openim_common/openim_common.dart';

class ChatFileView extends StatefulWidget {
  const ChatFileView({
    Key? key,
    required this.message,
    required this.isISend,
    this.downloadProgressStream,
  }) : super(key: key);
  
  final bool isISend;
  final Message message;
  final Stream<MsgStreamEv<int>>? downloadProgressStream;

  @override
  State<ChatFileView> createState() => _ChatFileViewState();
}

class _ChatFileViewState extends State<ChatFileView> {
  int _downloadProgress = 0;
  bool _isDownloading = false;
  bool _isPaused = false; // 新增暂停状态标记
  StreamSubscription? _progressSubscription;

  Message get message => widget.message;
  bool get isISend => widget.isISend;
  FileElem? get _fileElem => message.fileElem;

  @override
  void initState() {
    super.initState();
    _listenToProgress();
  }

  void _listenToProgress() {
    _progressSubscription = widget.downloadProgressStream?.listen((event) {
      if (event.id == message.clientMsgID) {
        _updateDownloadProgress(event.value);
      }
    });
  }

  void _updateDownloadProgress(int progress) {
    if (mounted) {
      setState(() {
        if (progress < 0) {
          // 暂停状态，负数表示暂停，绝对值为当前进度
          _isDownloading = false;
          _isPaused = true;
          _downloadProgress = progress.abs(); // 取绝对值作为显示进度
        } else if (progress == 0) {
          // 重置状态
          _isDownloading = false;
          _isPaused = false;
          _downloadProgress = 0;
        } else if (progress == 100) {
          // 下载完成
          _isDownloading = false;
          _isPaused = false;
          _downloadProgress = 100;
        } else {
          // 下载中
          _isDownloading = true;
          _isPaused = false;
          _downloadProgress = progress;
        }
      });
    }
  }

  String _getDownloadStatusText() {
    final fileSize = IMUtils.formatBytes(_fileElem?.fileSize ?? 0);
    
    if (_isDownloading) {
      // 正在下载
      return '正在下载 $_downloadProgress% (点击暂停)';
    } else if (_isPaused && _downloadProgress > 0) {
      // 已暂停
      return '已暂停 $_downloadProgress% (点击继续)';
    } else if (_downloadProgress > 0 && _downloadProgress < 100) {
      // 下载未完成但不在下载中（可能是网络错误等）
      return '下载中断 $_downloadProgress% (点击重试)';
    } else if (_downloadProgress == 100) {
      // 下载完成
      return fileSize;
    } else {
      // 未开始下载
      return fileSize;
    }
  }
  @override
  void dispose() {
    _progressSubscription?.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final fileName = _fileElem?.fileName ?? '未知文件';
    final fileSize = _formatFileSize(_fileElem?.fileSize ?? 0);
    
    return Container(
      constraints: BoxConstraints(
        maxWidth: 247.w,
        minWidth: 120.w,
      ),
      padding: EdgeInsets.all(12.w),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          Row(
            mainAxisSize: MainAxisSize.min,
            children: [
              // 文件图标
              Container(
                width: 40.w,
                height: 40.w,
                decoration: BoxDecoration(
                  color: Styles.c_0089FF.withOpacity(0.1),
                  borderRadius: BorderRadius.circular(8.r),
                ),
                child: Stack(
                  alignment: Alignment.center,
                  children: [
                    Icon(
                      _getFileIcon(fileName),
                      color: Styles.c_0089FF,
                      size: 24.w,
                    ),
                    if (_isDownloading)
                      CircularProgressIndicator(
                        value: _downloadProgress / 100.0,
                        strokeWidth: 2.w,
                        color: Styles.c_0089FF,
                        backgroundColor: Colors.grey.withOpacity(0.3),
                      ),
                  ],
                ),
              ),
              12.horizontalSpace,
              // 文件信息
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Text(
                      fileName,
                      style: TextStyle(
                        fontSize: 14.sp,
                        fontWeight: FontWeight.w500,
                        color: isISend ? Styles.c_FFFFFF : Styles.c_0C1C33,
                      ),
                      maxLines: 2,
                      overflow: TextOverflow.ellipsis,
                    ),
                    4.verticalSpace,
                    Text(
                      _getDownloadStatusText(),
                      style: TextStyle(
                        fontSize: 12.sp,
                        color: (isISend ? Styles.c_FFFFFF : Styles.c_8E9AB0).withOpacity(0.8),
                      ),
                    ),
                  ],
                ),
              ),
            ],
          ),
          // 下载进度条
          if (_isDownloading || _isPaused) ...[
            8.verticalSpace,
            LinearProgressIndicator(
              value: _downloadProgress / 100.0,
              backgroundColor: Colors.grey.withOpacity(0.3),
              valueColor: AlwaysStoppedAnimation<Color>(
                _isPaused 
                  ? Colors.orange // 暂停时显示橙色
                  : (isISend ? Styles.c_FFFFFF : Styles.c_0089FF), // 下载中显示蓝色
              ),
              minHeight: 2.h,
            ),
          ],
        ],
      ),
    );
  }

  IconData _getFileIcon(String fileName) {
    final extension = fileName.toLowerCase().split('.').last;
    
    switch (extension) {
      case 'pdf':
        return Icons.picture_as_pdf;
      case 'doc':
      case 'docx':
        return Icons.description;
      case 'xls':
      case 'xlsx':
        return Icons.table_chart;
      case 'ppt':
      case 'pptx':
        return Icons.slideshow;
      case 'txt':
        return Icons.text_snippet;
      case 'zip':
      case 'rar':
      case '7z':
        return Icons.archive;
      case 'jpg':
      case 'jpeg':
      case 'png':
      case 'gif':
        return Icons.image;
      case 'mp4':
      case 'avi':
      case 'mov':
        return Icons.video_file;
      case 'mp3':
      case 'wav':
      case 'flac':
        return Icons.audio_file;
      default:
        return Icons.insert_drive_file;
    }
  }

  String _formatFileSize(int bytes) {
    if (bytes <= 0) return '0 B';
    
    const suffixes = ['B', 'KB', 'MB', 'GB', 'TB'];
    int i = 0;
    double size = bytes.toDouble();
    
    while (size >= 1024 && i < suffixes.length - 1) {
      size /= 1024;
      i++;
    }
    
    return '${size.toStringAsFixed(size < 10 ? 1 : 0)} ${suffixes[i]}';
  }
}